package org.axed.user.client.util;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import java.util.Stack;
import org.axed.user.client.util.Profiler;
import org.axed.user.client.util.ProfileEntry;

/**
 * Shows the profiler contents
 */
public class ProfilerDialog extends DialogBox {
	Button okButton = new Button("OK");
	VerticalPanel vz = new VerticalPanel();
	Tree tree = new Tree();

	public ProfilerDialog() {
		super(false, false);
		DOM.setStyleAttribute(getElement(), "zIndex", "100");
		setWidget(vz);
		vz.add(tree);
		vz.add(okButton);
		
		TreeItem ti = new TreeItem("Profile Linear"); // tree item
		for (int i = 0; i < Profiler.times.size(); i++) {
			ProfileEntry e = (ProfileEntry) Profiler.times.get(i);
			TreeItem ni = new TreeItem(e.name + ": " + (e.end - e.begin) + " (" + e.level + ")");
			ti.addItem(ni);
		}
		tree.addItem(ti);
	
		ti = new TreeItem("Profile Tree"); // tree item
		TreeItem li = ti; // last item
		// ni = new item
		tree.addItem(ti);
		Stack stack = new Stack();

		for (int i = 0; i < Profiler.times.size(); i++) {
			ProfileEntry e = (ProfileEntry) Profiler.times.get(i);
			if (e.level == stack.size()) {
				TreeItem ni = new TreeItem(e.name + ": " + (e.end - e.begin));
				ti.addItem(ni);
				li = ni;
			} else if (e.level > stack.size()) {
				TreeItem ni = new TreeItem(e.name + ": " + (e.end - e.begin));
				li.addItem(ni); 
				stack.push(ti);
				ti = li;
				li = ni;
			} else {
				while (e.level < stack.size()) {
					ti = (TreeItem) stack.pop();
				}
				TreeItem ni = new TreeItem(e.name + ": " + (e.end - e.begin));
				ti.addItem(ni);
				li = ni;
			}
		}
		
		
		setText("Profiler");
		setStyleName("bluebg");
		
		okButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				hide();
			}
		});
	}
}
